package pers.cj.pdos.utils;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    //乘
    public synchronized static double getMultiply(double x,double y){
        BigDecimal x1 = new BigDecimal(Double.valueOf(x));
        BigDecimal y1 = new BigDecimal(Double.valueOf(y));
        return x1.multiply(y1).doubleValue();
    }

    //除
    public synchronized static double getDivide(double x,double y){
        BigDecimal x1 = new BigDecimal(Double.valueOf(x));
        BigDecimal y1 = new BigDecimal(Double.valueOf(y));
        return x1.divide(y1).doubleValue();
    }

    /**
     * Double类型数据保留num位四舍五入处理转String类型
     * @param value - 数值
     * @param num - 保留小数点后几位
     * @return
     */
    public synchronized static String getFloatStr(Double value,int num) {
        return String.format("%."+num+"f", value);
    }

    public synchronized static String getFloatStr(String value,int num) {
        return getFloatStr(Double.parseDouble(value), num);
    }

    public synchronized static boolean isTrue(Boolean flag) {
        if (flag!=null && flag) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 字符串是否仅包含数字和字母
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        if (Utils.isEmpty(str)) {
            return false;
        }
        String regex = "^[a-z0-9A-Z]+$";
        return str.matches(regex);
    }

    /**
     * 采用正则表达式的方式来判断一个字符串是否为数字，这种方式判断面比较全\
     * 可以判断正负、整数小数
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        if (Utils.isEmpty(str)) {
            return false;
        }
        return isInt(str) || isFloat(str);
    }

    /**
     * 是否是正整数
     * @param str
     * @return
     */
    public static boolean isIntAdd(String str) {
        return Pattern.compile("^[+]{0,1}(\\d+)$").matcher(str).find();
    }

    /**
     * 是否是整数(包含正数和负数)
     * @param str
     * @return
     */
    public static boolean isInt(String str) {
        return Pattern.compile("^-?[1-9]\\d*$").matcher(str).find();
    }

    /**
     * 是否是整数(包含正数和负数)
     * @param decimal
     * @return
     */
    public static boolean isInt(BigDecimal decimal) {
        return decimal.intValue() == decimal.doubleValue();
    }

    /**
     * 是否是小数
     * @param str
     * @return
     */
    public static boolean isFloat(String str) {
        return Pattern.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$").matcher(str).find();
    }

    public static boolean check(List<Long> list){
        if (Utils.isEmpty(list)){
            return false;
        }
        boolean flag = false;
        for (int i=0;i<list.size();i++) {
            if (list.get(i) > 0) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    public static Date genDate(String date) {
        if (isEmpty(date)) {
            return null;
        }

        return DateUtils.genDate(date, DateUtils.YYYY_MM_DD);

    }

    public static Integer genInteger(String data) {
        if (isEmpty(data)) {
            return null;
        }
        try {
            return Integer.parseInt(data);
        } catch (Exception e){
            return null;
        }
    }

    public static Boolean genBoolean(String data) {
        if (isEmpty(data)) {
            return null;
        }
        try {
            return Boolean.parseBoolean(data);
        } catch (Exception e){
            return null;
        }
    }

    public static String genLikeData(String data) {
        if (isEmpty(data)) {
            return null;
        }
        return "%" + data + "%";
    }

    public static Integer genPage(Integer page, Integer limit) {
        if (page!=null && limit!=null) {
            return (page-1)*limit;
        }
        return null;
    }

    public static boolean isEmpty(String data) {
        if (data == null) {
            return true;
        }
        data = data.trim();
        if ("".equals(data)) {
            return true;
        }
        return false;
    }

    public synchronized static boolean isEmpty(List list){
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }

    public synchronized static boolean isEmpty(Object[] objects){
        if (objects != null && objects.length != 0) {
            return false;
        }
        return true;
    }

    /**
     * 读取远程url图片,得到宽高
     * @param imgurl 图片路径
     * @return [0] 宽  [1]高
     */
    public static int[] getImgWH(String imgurl) {
        boolean b=false;
        try {
            //实例化url
            URL url = new URL(imgurl);
            //载入图片到输入流
            BufferedInputStream bis = new BufferedInputStream(url.openStream());
            //实例化存储字节数组
            byte[] bytes = new byte[100];
            //设置写入路径以及图片名称
            OutputStream bos = new FileOutputStream(new File("pic.jpg"));
            int len;
            while ((len = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.flush();
            bos.close();
            //关闭输出流
            b=true;
        } catch (Exception e) {
            //如果图片未找到
            b=false;
        }
        int[] a = new int[2];
        if(b){//图片存在
            //得到文件
            File file = new File("pic.jpg");
            BufferedImage bi = null;
            boolean imgwrong=false;
            try {
                //读取图片
                bi = javax.imageio.ImageIO.read(file);
                try{
                    //判断文件图片是否能正常显示,有些图片编码不正确
                    int i = bi.getType();
                    imgwrong=true;
                }catch(Exception e){
                    imgwrong=false;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if(imgwrong){
                a[0] = bi.getWidth(); //获得 宽度
                a[1] = bi.getHeight(); //获得 高度
            }else{
                a=null;
            }
            //删除文件
            file.delete();
        }else{//图片不存在
            a=null;
        }
        return a;
    }

    /**
     * 获取html中图片的src属性
     * @param content
     * @param hostUrl
     * @return
     */
    public static List<String> getLocalImgSrc(String content, String hostUrl){
        List<String> list = new ArrayList<>();
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        Pattern p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        Matcher m_image = p_image.matcher(content);


        while (m_image.find()) {
            // 得到<img />数据
            String img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                String src = m.group(1);
                src = src.replace("'","");
                if (src.startsWith(hostUrl)) {
                    list.add(src.replace(hostUrl,""));
                }
                else {
                    String [] split = hostUrl.split("/");
                    String hostName = "/" + split[split.length-1];
                    if (src.startsWith(hostName)){
                        String url = src.substring(hostName.length()+1);
                        list.add(url);
                    }
                }
            }
        }
        return list;
    }


    /*
     *计算time2减去time1的差值 差值只设置 几天 几个小时 或 几分钟
     * 根据差值返回多长之间前或多长时间后
     * */
    public static String getDistanceTime(long time1, long time2) {

        long year = 0;
        long month = 0;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff;

        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }

        year = diff / (12 * 30 * 24 * 60 * 60 * 1000);
        month = diff / (30 * 24 * 60 * 60 * 1000);
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

        if (year != 0) return day + "年";
        if (month != 0) return month + "天";
        if (day != 0) return day + "天";
        if (hour != 0) return hour + "小时";
        if (min != 0) return min + "分钟";
        if (sec != 0) return sec + "秒" ;
        return "0秒";
    }

    public static String formatDate(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    public static int countPage(int count, int num){
        int page = count / num;
        if(count % num != 0){
            page++;
        }
        return page;
    }

    /**
     * 比较d1和d2大小
     * @param d1
     * @param d2
     * @return 1:d1>d2  0:d1=d2 -1:d1<d2
     */
    public static int compare(String d1,String d2){
        BigDecimal v1 = new BigDecimal(d1);  //创建大数据对象
        BigDecimal v2 = new BigDecimal(d2);
        return v1.compareTo(v2);
    }

    public static String sub(String d1,String d2){
        BigDecimal v1 = new BigDecimal(d1);  //创建大数据对象
        BigDecimal v2 = new BigDecimal(d2);
        return v1.subtract(v2).toString();
    }


    public static String add(String d1,String d2){
        BigDecimal v1 = new BigDecimal(d1);  //创建大数据对象
        BigDecimal v2 = new BigDecimal(d2);
        return v1.add(v2).toString();
    }
}
